package main

import (
	"context"
	"flag"
	"fmt"
	"net/http"
	"strings"

	"dfx_cmdb/cmdb-blacklist-rpc/internal/config"
	"dfx_cmdb/cmdb-blacklist-rpc/internal/global"
	"dfx_cmdb/cmdb-blacklist-rpc/internal/svc"
	cmdb_blacklist_rpc "dfx_cmdb/cmdb-blacklist-rpc/types/cmdb-blacklist-rpc"

	//xxl_job_admin "gitee.com/daofeixian/dfx_golang_toolset/xxl_job_admin"
	blacklistoperationServer "dfx_cmdb/cmdb-blacklist-rpc/internal/server/blacklistoperation"
	ignoreruleoperationServer "dfx_cmdb/cmdb-blacklist-rpc/internal/server/ignoreruleoperation"

	"github.com/go-chi/chi/v5"
	"github.com/zeromicro/go-zero/core/conf"
	"github.com/zeromicro/go-zero/core/service"
	"github.com/zeromicro/go-zero/zrpc"
	"google.golang.org/grpc"
	"google.golang.org/grpc/reflection"
)

var configFile = flag.String("f", "etc/cmdbblacklistrpc.yaml", "the config file")

func main() {
	flag.Parse()

	var c config.Config
	conf.MustLoad(*configFile, &c)
	ctx := svc.NewServiceContext(c)

	// 初始化已启用的黑名单定时任务，并刷新状态 Map

	err := global.InitCronJob(context.Background(), ctx)
	if err != nil {
		fmt.Printf("InitCronJob failed: %v\n", err)
	}

	ctx.Exec.Start()
	defer ctx.Exec.Stop()

	s := zrpc.MustNewServer(c.RpcServerConf, func(grpcServer *grpc.Server) {
		cmdb_blacklist_rpc.RegisterBlacklistOperationServer(grpcServer, blacklistoperationServer.NewBlacklistOperationServer(ctx))
		cmdb_blacklist_rpc.RegisterIgnoreRuleOperationServer(grpcServer, ignoreruleoperationServer.NewIgnoreRuleOperationServer(ctx))
		if c.Mode == service.DevMode || c.Mode == service.TestMode {
			reflection.Register(grpcServer)
		}
	})
	defer s.Stop()

	// 规范化路由路径，避免出现 //xxl-job 导致 301 或 404
	path := "/" + strings.TrimPrefix(ctx.Config.XxlJobAdmin.XxlJobExecutor.Uri, "/")
	handler := ctx.Exec.Handle(path)
	// xxl_job_admin.ListenHttpRun(path, handler, ctx.Config.XxlJobAdmin.XxlJobExecutor.Addr, ctx.Config.XxlJobAdmin.XxlJobExecutor.Port)

	mux := chi.NewMux()
	mux.Mount(path, handler)
	go http.ListenAndServe(fmt.Sprintf("%s:%d", ctx.Config.XxlJobAdmin.XxlJobExecutor.Listen, ctx.Config.XxlJobAdmin.XxlJobExecutor.Port), mux)
	fmt.Printf("Starting rpc server at %s...\n", c.ListenOn)
	s.Start()
}
